package cn.ehanghai.iot.utils;

import com.alibaba.fastjson.JSONObject;
import me.chanjar.weixin.common.util.RandomUtils;
import net.ryian.commons.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class HttpUitl {
    private static final Logger LOG = LoggerFactory.getLogger(HttpUitl.class);
    public static String HTTP_URL = "http://www.zgsc123.com/index.php?m=content&c=price&a=pricelist_ajax";


    public static JSONObject sendPost(String url, String param, String characterSet) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        JSONObject response = new JSONObject();
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "application/json, text/javascript, */*; q=0.01");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            if (!StringUtils.isEmpty(characterSet)) {
                in = new BufferedReader(
                        new InputStreamReader(conn.getInputStream(), characterSet));
            } else {
                in = new BufferedReader(
                        new InputStreamReader(conn.getInputStream()));
            }
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            LOG.error("发送 POST 请求出现异常！", e);
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                LOG.error("发送 POST 请求出现异常！", ex);
            }
        }
        if (result.length() > 0) {
            response = JSONObject.parseObject(result);
        }
        return response;
    }

    /**
     * post方法放在body里
     *
     * @param url
     * @param json
     * @param headers
     * @return
     */
    @SuppressWarnings("deprecation")
    public static JSONObject readContentFromPost(String url, JSONObject json, Map<String, String> headers) {
        @SuppressWarnings("resource")
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        JSONObject response = null;
        post.setHeader("Content-Type", "application/json");
        if (headers != null) {
            Set<String> keys = headers.keySet();
            for (Iterator<String> i = keys.iterator(); i.hasNext(); ) {
                String key = (String) i.next();
                post.addHeader(key, headers.get(key));
            }
        }

        try {
            StringEntity s = null;
            if (json != null) {
                s = new StringEntity(json.toString(), "utf-8");
                s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                post.setEntity(s);
            }
            HttpResponse httpResponse = client.execute(post);
            InputStream inStream = httpResponse.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"));
            StringBuilder strber = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null)
                strber.append(line + "\n");
            inStream.close();
            if (strber.length() > 0) {
                response = JSONObject.parseObject(strber.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

    public static String sendPostGetString(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        JSONObject response = new JSONObject();
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "application/json, text/javascript, */*; q=0.01");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            LOG.error("发送 POST 请求出现异常！", e);
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                LOG.error("发送 POST 请求出现异常！", ex);
            }
        }

        return result;
    }


    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url   发送请求的URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
//                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    public static Document getDocument(String url) {
        try {
            return Jsoup.connect(url).get();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getPhoneAddress(String phoneNum) {
        String a = "";
        try {
//    		Document doc = getDocument("http://www.ip138.com:8080/search.asp?mobile="+phoneNum+"&action=mobile");
//            
////    		Document doc = getDocument("http://10.47.132.85:9876/search.asp?mobile="+phoneNum+"&action=mobile");
//            // 获取目标HTML代码
//            String aa = doc.toString();
//            aa=new String(aa.getBytes(), "gb2312");
////            System.out.println(aa);
//            if(aa.indexOf("<!-- <td width=\"138\" align=\"center\">卡号归属地</TD> -->")>-1){
//           	 aa=aa.substring(aa.indexOf("<!-- <td width=\"138\" align=\"center\">卡号归属地</TD> -->")).replace("<!-- <td width=\"138\" align=\"center\">卡号归属地</TD> -->","");
//            }else if(aa.indexOf("<td width=\"138\" align=\"center\" noswap=\"\">卡号归属地</td>")>-1){
//           	 aa=aa.substring(aa.indexOf("<td width=\"138\" align=\"center\" noswap=\"\">卡号归属地</td>")).replace("<td width=\"138\" align=\"center\" noswap=\"\">卡号归属地</td>","");
//            }else if(aa.indexOf("<!-- <td></td> -->")>-1){
//           	 aa=aa.substring(aa.indexOf("<!-- <td></td> -->")).replace("<!-- <td></td> -->","");
//            }
//
////            System.out.println(aa);
//            a = aa.replace("<td width=\"*\" align=\"center\" class=\"tdc2\">", "").replace("<td class=\"tdc2\" align=\"center\">", "");
//            a=a.substring(0, a.indexOf("</td>"));
//            a=a.replace("&nbsp;", "-");
//            if(a.substring(a.length()-1).equals("-")){
//            	a=a.substring(0,a.length()-1);
//            }
//            System.out.println(a);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }


        return a;
    }

    public static void main(String[] args) {
        try {
//			getPhoneAddress("13546876909");
//			getPhoneAddress("13666589658");
//			getPhoneAddress("15140605550");
            String appId = "wx5809dd62a0b47a48";
            String secret = "cef2e817ea918c9366cc44c484e4fac5";
            String url = "https://api.weixin.qq.com/cgi-bin/token";
            String param = "grant_type=client_credential&appid=" + appId + "&secret=" + secret + "";
            String result = sendGet(url, param);
            net.sf.json.JSONObject json = net.sf.json.JSONObject.fromObject(result);
            String accessToken = (String) json.get("access_token");
            System.out.println(accessToken);
            String ticketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
            String ticketParam = "access_token=" + accessToken + "&type=jsapi";
            String result1 = HttpUitl.sendGet(ticketUrl, ticketParam);
            System.out.println(result1);
            long timestamp = System.currentTimeMillis() / 1000L;
            System.out.println(timestamp);
            String noncestr = RandomUtils.getRandomStr();
            System.out.println(noncestr);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    public static JSONObject sendGetJson(String url, String param, String characterSet) {
        JSONObject object = new JSONObject();
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            if (!StringUtils.isEmpty(characterSet)) {
                in = new BufferedReader(
                        new InputStreamReader(connection.getInputStream(), characterSet));
            } else {
                in = new BufferedReader(
                        new InputStreamReader(connection.getInputStream()));
            }
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            object = JSONObject.parseObject(result);
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return object;
    }

    public static String stringToUnicode(String s) {
        try {
            StringBuffer out = new StringBuffer("");
            //直接获取字符串的unicode二进制
            byte[] bytes = s.getBytes("unicode");
            //然后将其byte转换成对应的16进制表示即可
            for (int i = 0; i < bytes.length - 1; i += 2) {
                out.append("\\u");
                String str = Integer.toHexString(bytes[i + 1] & 0xff);
                for (int j = str.length(); j < 2; j++) {
                    out.append("0");
                }
                String str1 = Integer.toHexString(bytes[i] & 0xff);
                out.append(str1);
                out.append(str);
            }
            return out.toString().replace("\\ufeff", "");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }
}
